﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Security;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Web;

using System.Drawing;
using System.Security.Cryptography;
using System.Data.OleDb;
using System.Diagnostics;

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Web.Script.Serialization;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;
using System.Net.NetworkInformation;

namespace LaneLpnr.Utils
{
    public class DataChage
    {
        public static bool IsRightIP(string strLocalIP)
        {
            bool bFlag = false;
            bool Result = true;

            Regex regex = new Regex("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$");
            bFlag = regex.IsMatch(strLocalIP);
            if (bFlag == true)
            {
                string[] strTemp = strLocalIP.Split(new char[] { '.' });
                int nDotCount = strTemp.Length - 1; //字符串中.的数量，若.的数量小于3，则是非法的ip地址
                if (3 == nDotCount)//判断 .的数量
                {
                    for (int i = 0; i < strTemp.Length; i++)
                    {
                        if (Convert.ToInt32(strTemp[i]) > 255)   //大于255不符合返回false
                        {
                            Result = false;
                        }
                    }
                }
                else
                {
                    Result = false;
                }
            }
            else
            {
                //输入非数字则提示，不符合IP格式
                //MessageBox.Show("不符合IP格式");
                Result = false;
            }
            return Result;

        }

        public static bool IsPingIP(string strLocalIP)
        {
            bool Result = true;
            if (strLocalIP != string.Empty)
            {
                Ping pingSender = new Ping();
                PingReply inreply = pingSender.Send(strLocalIP, 5);

                if (inreply.Status == IPStatus.Success)
                {
                    Result = true;
                }
                else
                {
                    Result = false;
                }
            }
            else
            {
                Result = false;
            }
            return Result;
        }



        /// <summary>
        /// 产生随机数
        /// </summary>
        /// <returns></returns>
        public static string GetGuid()
        {
            return Guid.NewGuid().ToString();
        }


        /// <summary>
        /// 加密的随机数
        /// </summary>
        /// <returns></returns>
        public static string GetRNG()
        {
            RNGCryptoServiceProvider csp = new RNGCryptoServiceProvider();
            byte[] byteCsp = new byte[15];
            csp.GetBytes(byteCsp);
            return (BitConverter.ToString(byteCsp));
        }


        /// <summary>
        /// 取时间戳，高并发情况下会有重复。想要解决这问题请使用sleep线程睡眠1毫秒。
        /// </summary>
        /// <param name="AccurateToMilliseconds">精确到秒</param>
        /// <returns>返回一个长整数时间戳</returns>
        public static long GetTimeStamp(DateTime time, bool AccurateToMilliseconds = false)
        {
            if (AccurateToMilliseconds)
            {

                // 使用当前时间计时周期数（636662920472315179）减去1970年01月01日计时周期数（621355968000000000）除去（删掉）后面4位计数（后四位计时单位小于毫秒，快到不要不要）再取整（去小数点）。

                //备注：DateTime.Now.ToUniversalTime不能缩写成DateTime.Now.Ticks，会有好几个小时的误差。

                //621355968000000000计算方法 long ticks = (new DateTime(1970, 1, 1, 8, 0, 0)).ToUniversalTime().Ticks;

                return (time.Ticks - 621355968000000000) / 10000;

                //return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000;

            }
            else
            {

                //上面是精确到毫秒，需要在最后除去（10000），这里只精确到秒，只要在10000后面加三个0即可（1秒等于1000毫米）。
                return (time.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
                //return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
            }
        }



        public static string ConvertJsonString(string str)
        {
            try
            {
                //格式化json字符串
                JsonSerializer serializer = new JsonSerializer();
                TextReader tr = new StringReader(str);
                JsonTextReader jtr = new JsonTextReader(tr);
                object obj = serializer.Deserialize(jtr);
                if (obj != null)
                {
                    StringWriter textWriter = new StringWriter();
                    JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                    {
                        Formatting = Formatting.Indented,
                        Indentation = 4,
                        IndentChar = ' '
                    };
                    serializer.Serialize(jsonWriter, obj);
                    return textWriter.ToString();
                }
                else
                {
                    return str;
                }
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("异常ConvertJsonString" + ex.ToString());
                return null;
            }
        }


        /// <summary>
        /// 图片转base64
        /// </summary>
        /// <param name="Imagefilename"></param>
        /// <returns></returns>
        public static string ImgToBase64String(string Imagefilename)
        {
            try
            {
                if (Imagefilename != null && Imagefilename.Length != 0)
                {
                    if (File.Exists(Imagefilename))
                    {
                        Bitmap bmp = new Bitmap(Imagefilename);

                        MemoryStream ms = new MemoryStream();
                        bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                        byte[] arr = new byte[ms.Length];
                        ms.Position = 0;
                        ms.Read(arr, 0, (int)ms.Length);
                        ms.Close();
                        return Convert.ToBase64String(arr);
                    }
                    else
                    {
                        FlashLog.FlashLogger.Debug("文件不存在:" + Imagefilename);
                        return "";

                    }
                }
                else
                {
                    return "";
                }
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("异常ImgToBase64String" + ex.ToString());
                return "";
            }
        }

        public static String ByteToString(byte[] bytes)
        {

            StringBuilder strBuilder = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                strBuilder.Append(Convert.ToChar(bytes[i]));

            }
            return strBuilder.ToString();
        }








    }





}
